<template>
  <div class="main">
    <a-form
      id="formLogin"
      class="user-layout-login"
      ref="formLogin"
      :form="form"
      @submit="handleSubmit"
    >
      <a-tabs
        :activeKey="customActiveKey"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
      >
        <a-tab-pane key="tab1" :tab="$t('user.login.tab-login-credentials')">
          <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px;" :message="$t('user.login.message-invalid-credentials')" />
          <a-form-item>
            <a-input
              size="large"
              type="text"
              :placeholder="$t('user.login.username.placeholder')"
              v-decorator="[
                'account',
                {rules: [{ required: true, pattern: /^1[3456789]\d{9}$/, message: $t('user.login.mobile.placeholder') }], validateTrigger: 'change'}
              ]"
            >
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>

          <a-form-item>
            <a-input-password
              size="large"
              :placeholder="$t('user.login.password.placeholder')"
              v-decorator="[
                'password',
                {rules: [{ required: true, message: $t('user.password.required') }], validateTrigger: 'blur'}
              ]"
            >
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input-password>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="tab2" :tab="$t('user.login.tab-login-mobile')">
          <a-form-item>
            <a-input size="large" type="text" :placeholder="$t('user.login.mobile.placeholder')" v-decorator="['phone', {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: $t('user.login.mobile.placeholder') }], validateTrigger: 'change'}]">
              <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>

          <a-row :gutter="16">
            <a-col class="gutter-row" :span="16">
              <a-form-item>
                <a-input size="large" type="text" :placeholder="$t('user.login.mobile.verification-code.placeholder')" v-decorator="['authCode', {rules: [{ required: true, message: $t('user.verification-code.required') }], validateTrigger: 'blur'}]">
                  <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button
                class="getCaptcha"
                tabindex="-1"
                :disabled="state.smsSendBtn"
                @click.stop.prevent="getCaptcha"
                v-text="!state.smsSendBtn && $t('user.register.get-verification-code') || (state.time+' s')"
              ></a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>

      <!-- <a-form-item>
        <a-checkbox v-decorator="['rememberMe', { valuePropName: 'checked' }]">{{ $t('user.login.remember-me') }}</a-checkbox>
        <router-link
          :to="{ name: 'recover', params: { user: 'aaa'} }"
          class="forge-password"
          style="float: right;"
        >{{ $t('user.login.forgot-password') }}</router-link>
      </a-form-item> -->

      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
        >{{ $t('user.login.login') }}</a-button>
      </a-form-item>

      <div class="user-login-other">
        <!-- <span>{{ $t('user.login.sign-in-with') }}</span>
        <a>
          <a-icon class="item-icon" type="alipay-circle"></a-icon>
        </a>
        <a>
          <a-icon class="item-icon" type="taobao-circle"></a-icon>
        </a>
        <a>
          <a-icon class="item-icon" type="weibo-circle"></a-icon>
        </a> -->
        <!-- <router-link class="register" :to="{ name: 'register' }">{{ $t('user.login.signup') }}</router-link> -->
      </div>
    </a-form>

    <Verify
      ref="verify"
      mode="pop"
      :captcha-type="'blockPuzzle'"
      :img-size="{width:'400px',height:'200px'}"
      @success="verSuccess"
    ></Verify>

  </div>
</template>

<script>
import md5 from 'md5'
import { mapActions } from 'vuex'
import { timeFix , getHashParam } from '@/utils/util'
import { getSmsCaptcha, getServeToken } from '@/api/login';
import { queryMember } from '@/api/member';
import { queryGoodsMerchantInfo } from '@/api/newMall';
import { ACCESS_TOKEN } from '@/store/mutation-types'
import storage from 'store'
import Verify from '@/components/verifition/Verify'

export default {
  components: {
    Verify
  },
  data () {
    return {
      customActiveKey: 'tab2',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      },
      brandId: this.global.brandId,
      permissions: true,
      perPhoneList: [
        13641844258,18738108782
      ],
      loginParams: {},
    }
  },
  created () {
    // if(process.env.NODE_ENV == 'development'){
    //   this.permissions = false
    // }
    this.permissions = false
    storage.clearAll()
    sessionStorage.clear()
    // 获取客户端token
    getServeToken({'brandId':this.brandId})
    .then(res=>{
      console.log(res)
      if(res.success){
        // storage.set(ACCESS_TOKEN,res[ACCESS_TOKEN])
        sessionStorage.setItem(ACCESS_TOKEN,res[ACCESS_TOKEN])
        if(getHashParam('phone')){
          this._autoLogin();
        }
      }
    })
  },
  methods: {
    ...mapActions(['Login', 'Logout', 'LoginCode']),
    // handler
    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick (key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login,
        LoginCode
      } = this

      state.loginBtn = true

      const validateFieldsKey = customActiveKey === 'tab1' ? ['account', 'password'] : ['phone', 'authCode']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          console.log('login form', values)
          const loginParams = { ...values }
          const loginApi = customActiveKey === 'tab1' ? Login : LoginCode
          // if(this.permissions){
          //   let phone = customActiveKey === 'tab1' ? loginParams['account'] : loginParams['phone']
          //   sessionStorage.setItem('loginPhone',phone)
          //   if(this.perPhoneList.indexOf(phone) == -1){
          //     this.$notification['error']({
          //         message: '提示',
          //         description: '当前账号暂无登录权限！',
          //         duration: 8
          //     })
          //     state.loginBtn = false
          //     return
          //   }
          // }
          let phone = customActiveKey === 'tab1' ? loginParams['account'] : loginParams['phone']
          sessionStorage.setItem('loginPhone',phone)
          // if(customActiveKey === 'tab1'){
          //   this.loginParams = loginParams;
          //   this.$refs.verify.show()
          //   state.loginBtn = false
          // }else{
          //   loginApi(loginParams).then((res) => this.loginSuccess(phone))
          //   .catch(err => this.requestFailed(err))
          //   .finally(() => {
          //     state.loginBtn = false
          //   })
          // }
          loginApi(loginParams).then((res) => this.loginSuccess(phone))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          console.log('111')
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    verSuccess(){
      let _this = this
      _this.Login(_this.loginParams).then((res) => _this.loginSuccess(_this.loginParams['account']))
            .catch(err => _this.requestFailed(err))
            .finally(() => {
              _this.state.loginBtn = false
            })
    },
    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state } = this

      validateFields(['phone'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)
          getSmsCaptcha({ receiveAccount: values.phone }).then(res => {
            if(res.success){
                setTimeout(hide, 500)
                this.$notification['success']({
                  message: '提示',
                  description: '验证码获取成功',
                  duration: 8
                })
              }else{
                setTimeout(hide, 500)
                this.$notification['error']({
                  message: '提示',
                  description: res.errMessage,
                  duration: 8
                })
              }
          }).catch(err => {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.time = 60
            state.smsSendBtn = false
            this.requestFailed(err)
          })
        }
      })
    },
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    async loginSuccess (phone) {
      console.log(phone)
      var userList = await this.queryUser(phone);
      await this.queryMerchant(userList[0].userId);
      sessionStorage.setItem('isLogin',true)
      this.$router.push({ path: '/mall/goodsOrder/order' })
      // 延迟 1 秒显示欢迎信息
      // setTimeout(() => {
      //   this.$notification.success({
      //     message: '欢迎',
      //     description: `${timeFix()}，欢迎回来`
      //   })
      // }, 1000)
      this.isLoginError = false
    },
    requestFailed (err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err || {}).errMessage ) || '请求出现错误，请稍后再试',
        duration: 4
      })
    },
    // 查询用户userId
        queryUser(phone){
            let _this = this
            const params = {
                'brandId':_this.brandId,
                'phone':phone,
            }
            return new Promise((reslove,reject) =>{
                queryMember(params)
                .then(res=>{
                    if(res.success){
                        reslove(res.data.content)
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 查询商户信息
        queryMerchant(userId){
            let _this = this;
          return new Promise((resolve,reject) => {
            const params = {
                'userId': userId,
                'brandId': _this.global.brandId,
                'page': 0,
                'size': 1,
            }
            queryGoodsMerchantInfo(params)
            .then(res=>{
                if(res.success){
                  if(res.data.content.length > 0){
                    sessionStorage.setItem('merchantId',res.data.content[0]['id'])
                    sessionStorage.setItem('merchantName',res.data.content[0]['storeName'])
                    resolve()
                  }else{
                    reject('暂无商户信息，请联系管理员确认！')
                  }
                }else{
                  reject(res.errMessage)
                }
            })
          })
        },
    // 自动登录
    _autoLogin(){
      const {
        Login,
      } = this
      const phone = getHashParam('phone')
      sessionStorage.setItem('loginPhone',phone)
      const loginParams = {
        'account': phone,
        'password': 'a123456'
      }
      Login(loginParams).then((res) => this.loginSuccess(phone))
      .catch(err => this.requestFailed(err))
      .finally(() => {
        state.loginBtn = false
      })
    },
  }
}
</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
